// lib/pages/statistic.dart
import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
import '../models/task.dart';
import '../theme/app_theme.dart';
import 'package:intl/intl.dart';
import 'pending_tasks_page.dart';
import 'dart:math';

enum StatViewMode { month, week, day }

class StatisticPage extends StatefulWidget {
  final List<Task> tasks;

  const StatisticPage({
    Key? key,
    required this.tasks,
  }) : super(key: key);

  @override
  _StatisticPageState createState() => _StatisticPageState();
}

class _StatisticPageState extends State<StatisticPage> with AppTheme, TickerProviderStateMixin {
  StatViewMode _currentViewMode = StatViewMode.month;
  late DateTime _selectedDate;
  late DateTime _currentMonth;
  late DateTime _currentWeek;

  // 动画控制器
  late AnimationController _animationController;
  late AnimationController _chartAnimationController;
  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;
  late Animation<double> _scaleAnimation;



  @override
  void initState() {
    super.initState();
    _selectedDate = DateTime.now();
    _currentMonth = DateTime(_selectedDate.year, _selectedDate.month, 1);
    _currentWeek = _selectedDate.subtract(Duration(days: _selectedDate.weekday % 7));
    
    // 初始化动画
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1000),
    );
    
    _chartAnimationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1200),
    );
    
    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _animationController,
        curve: const Interval(0.0, 0.6, curve: Curves.easeOut),
      ),
    );
    
    _slideAnimation = Tween<Offset>(
      begin: const Offset(0, -0.3),
      end: Offset.zero,
    ).animate(
      CurvedAnimation(
        parent: _animationController,
        curve: const Interval(0.2, 0.8, curve: Curves.easeOutCubic),
      ),
    );
    
    _scaleAnimation = Tween<double>(begin: 0.8, end: 1.0).animate(
      CurvedAnimation(
        parent: _chartAnimationController,
        curve: Curves.elasticOut,
      ),
    );
    
    _animationController.forward();
    _chartAnimationController.forward();
  }

  @override
  void dispose() {
    _animationController.dispose();
    _chartAnimationController.dispose();
    super.dispose();
  }

  // 获取指定时间范围内的任务
  List<Task> _getTasksInRange(DateTime start, DateTime end) {
    return widget.tasks.where((task) {
      final taskDate = DateTime(task.time.year, task.time.month, task.time.day);
      return !task.isDeleted && // 过滤掉已删除的任务
             taskDate.isAfter(start.subtract(const Duration(days: 1))) && 
             taskDate.isBefore(end.add(const Duration(days: 1)));
    }).toList();
  }

  // 获取统计数据
  Map<String, dynamic> _getStats(List<Task> tasks) {
    int total = tasks.length;
    int completed = tasks.where((t) => t.isCompleted).length;
    int onTime = 0;
    int late = 0;
    int early = 0;

    for (var task in tasks.where((t) => t.isCompleted)) {
      if (task.completedTime == null) continue;
      
      final completionTime = task.completedTime!;
      final scheduledTime = task.time;
      
      if (completionTime.isBefore(scheduledTime)) {
        early++;
      } else if (completionTime.isAfter(scheduledTime)) {
        late++;
      } else {
        onTime++;
      }
    }

    return {
      'total': total,
      'completed': completed,
      'onTime': onTime,
      'late': late,
      'early': early,
      'completionRate': total > 0 ? (completed / total) : 0,
    };
  }

  // 切换视图模式
  void _changeViewMode(StatViewMode mode) {
    setState(() {
      _currentViewMode = mode;
    });
  }

  // 总体统计概览
  Widget _buildOverallStatistics() {
    final allTasks = widget.tasks.where((task) => !task.isDeleted).toList();
    final completedTasks = allTasks.where((task) => task.isCompleted).toList();
    final pendingTasks = allTasks.where((task) => !task.isCompleted).toList();
    final overallCompletionRate = allTasks.isNotEmpty ? (completedTasks.length / allTasks.length) : 0.0;

    return SlideTransition(
      position: _slideAnimation,
      child: FadeTransition(
        opacity: _fadeAnimation,
        child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
                Container(
                  padding: const EdgeInsets.all(AppTheme.paddingS),
                  decoration: BoxDecoration(
                    gradient: AppTheme.primaryGradient,
                    borderRadius: BorderRadius.circular(AppTheme.radiusM),
                    boxShadow: [
                      BoxShadow(
                        color: AppTheme.primaryColor.withOpacity(0.3),
                        blurRadius: 8,
                        offset: const Offset(0, 4),
                      ),
                    ],
                  ),
                  child: const Icon(
                    Icons.analytics_rounded,
                    color: Colors.white,
                    size: 20,
                  ),
            ),
                const SizedBox(width: AppTheme.paddingM),
                const Text(
              '全部任务概览',
              style: TextStyle(
                    fontSize: AppTheme.fontSizeXL,
                    fontWeight: FontWeight.w700,
                    color: AppTheme.textPrimaryColor,
              ),
            ),
          ],
        ),
            const SizedBox(height: AppTheme.paddingL),
        Row(
          children: [
            Expanded(
              child: _buildQuickStatCard(
                '总任务',
                '${allTasks.length}',
                    AppTheme.infoColor,
                    Icons.list_alt_rounded,
                    LinearGradient(
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                      colors: [AppTheme.infoColor, Color(0xFF2563EB)],
                    ),
              ),
            ),
                const SizedBox(width: AppTheme.paddingM),
            Expanded(
              child: _buildQuickStatCard(
                '已完成',
                '${completedTasks.length}',
                    AppTheme.successColor,
                    Icons.check_circle_rounded,
                    AppTheme.successGradient,
              ),
            ),
                const SizedBox(width: AppTheme.paddingM),
             Expanded(
                  child: Material(
                    color: Colors.transparent,
                    child: InkWell(
                      borderRadius: BorderRadius.circular(AppTheme.radiusL),
                 onTap: () {
                   Navigator.push(
                     context,
                     MaterialPageRoute(
                       builder: (context) => PendingTasksPage(
                         tasks: widget.tasks,
                         onTaskUpdate: (task) {
                           // StatisticPage 不需要更新任务，只是查看
                         },
                       ),
                     ),
                   );
                 },
                 child: _buildQuickStatCard(
                   '待完成',
                   '${pendingTasks.length}',
                        AppTheme.warningColor,
                        Icons.schedule_rounded,
                        AppTheme.warningGradient,
                 ),
               ),
             ),
                ),
                const SizedBox(width: AppTheme.paddingM),
            Expanded(
              child: _buildQuickStatCard(
                '完成率',
                '${(overallCompletionRate * 100).toStringAsFixed(1)}%',
                    AppTheme.primaryColor,
                    Icons.pie_chart_rounded,
                    AppTheme.primaryGradient,
              ),
            ),
          ],
        ),
      ],
        ),
      ),
    );
  }

  // 快速统计卡片
  Widget _buildQuickStatCard(String title, String value, Color color, IconData icon, LinearGradient gradient) {
    return Container(
      padding: const EdgeInsets.all(AppTheme.paddingL),
      decoration: BoxDecoration(
        color: AppTheme.cardColor,
        borderRadius: BorderRadius.circular(AppTheme.radiusL),
        boxShadow: AppTheme.softShadow,
        border: Border.all(
          color: color.withOpacity(0.2),
          width: 1,
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            padding: const EdgeInsets.all(AppTheme.paddingS),
            decoration: BoxDecoration(
              gradient: gradient,
              borderRadius: BorderRadius.circular(AppTheme.radiusM),
              boxShadow: [
                BoxShadow(
                  color: color.withOpacity(0.3),
                  blurRadius: 8,
                  offset: const Offset(0, 4),
                ),
              ],
            ),
            child: Icon(
            icon,
              color: Colors.white,
              size: 18,
          ),
          ),
          const SizedBox(height: AppTheme.paddingS),
          Text(
            value,
            style: TextStyle(
              fontSize: AppTheme.fontSizeL,
              fontWeight: FontWeight.w700,
              color: color,
            ),
          ),
          const SizedBox(height: AppTheme.paddingXS),
          Text(
            title,
            style: const TextStyle(
              fontSize: AppTheme.fontSizeXS,
              color: AppTheme.textSecondaryColor,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  // 切换月份
  void _changeMonth(int delta) {
    final newMonth = DateTime(
      _currentMonth.year,
      _currentMonth.month + delta,
      1,
    );
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, 1);
    
    // 不允许查看未来月份
    if (newMonth.isAfter(today)) return;
    
    setState(() {
      _currentMonth = newMonth;
    });
  }

  // 切换周
  void _changeWeek(int delta) {
    final newWeek = _currentWeek.add(Duration(days: 7 * delta));
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    
    // 不允许查看未来周
    if (newWeek.isAfter(today)) return;
    
    setState(() {
      _currentWeek = newWeek;
    });
  }

  // 切换日期
  void _changeDate(int delta) {
    final newDate = _selectedDate.add(Duration(days: delta));
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    
    // 不允许查看未来日期
    if (newDate.isAfter(today)) return;
    
    setState(() {
      _selectedDate = DateTime(newDate.year, newDate.month, newDate.day);
    });
  }

  // 检查是否到达最新日期
  bool _isLatestDate() {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    
    if (_currentViewMode == StatViewMode.month) {
      return _currentMonth.year == today.year && _currentMonth.month == today.month;
    } else if (_currentViewMode == StatViewMode.week) {
      final weekEnd = _currentWeek.add(const Duration(days: 6));
      return weekEnd.isAfter(today) || weekEnd.isAtSameMomentAs(today);
    } else {
      // 日视图：如果当前日期等于或晚于今天，则禁用前进按钮
      final currentDate = DateTime(_selectedDate.year, _selectedDate.month, _selectedDate.day);
      return currentDate.isAfter(today) || currentDate.isAtSameMomentAs(today);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.backgroundColor,
      body: SafeArea(
        child: Column(
          children: [
            // 顶部容器
            Container(
              decoration: BoxDecoration(
                gradient: AppTheme.primaryGradient,
                boxShadow: AppTheme.strongShadow,
              ),
              child: Padding(
                padding: const EdgeInsets.all(AppTheme.paddingXL),
                child: SlideTransition(
                  position: _slideAnimation,
                  child: FadeTransition(
                    opacity: _fadeAnimation,
                    child: Column(
        children: [
                        // 顶部标题和视图切换
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            const Text(
                              '任务统计',
                              style: TextStyle(
                                fontSize: AppTheme.fontSizeXXL,
                                fontWeight: FontWeight.w700,
                                color: Colors.white,
                              ),
                            ),
          Container(
                              padding: const EdgeInsets.all(AppTheme.paddingXS),
                              decoration: BoxDecoration(
                                color: Colors.white.withOpacity(0.15),
                                borderRadius: BorderRadius.circular(AppTheme.radiusL),
                              ),
            child: Row(
              children: [
                _buildViewModeButton('月', StatViewMode.month),
                                  const SizedBox(width: AppTheme.paddingXS),
                _buildViewModeButton('周', StatViewMode.week),
                                  const SizedBox(width: AppTheme.paddingXS),
                _buildViewModeButton('日', StatViewMode.day),
              ],
            ),
          ),
                          ],
                        ),
                        const SizedBox(height: AppTheme.paddingL),
          // 日期导航
          Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: AppTheme.paddingL,
                            vertical: AppTheme.paddingM,
                          ),
                          decoration: BoxDecoration(
                            color: Colors.white.withOpacity(0.15),
                            borderRadius: BorderRadius.circular(AppTheme.radiusL),
                          ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                              Material(
                                color: Colors.transparent,
                                child: InkWell(
                                  borderRadius: BorderRadius.circular(AppTheme.radiusM),
                                  onTap: () {
                    if (_currentViewMode == StatViewMode.month) {
                      _changeMonth(-1);
                    } else if (_currentViewMode == StatViewMode.week) {
                      _changeWeek(-1);
                    } else {
                      _changeDate(-1);
                    }
                  },
                                  child: Container(
                                    padding: const EdgeInsets.all(AppTheme.paddingS),
                                    decoration: BoxDecoration(
                                      color: Colors.white.withOpacity(0.2),
                                      borderRadius: BorderRadius.circular(AppTheme.radiusM),
                                    ),
                                    child: const Icon(
                                      Icons.chevron_left_rounded,
                                      color: Colors.white,
                                      size: 24,
                                    ),
                                  ),
                                ),
                ),
                Text(
                  _currentViewMode == StatViewMode.month
                      ? DateFormat('yyyy年MM月').format(_currentMonth)
                      : _currentViewMode == StatViewMode.week
                          ? '${DateFormat('M').format(_currentWeek)}月第${_getWeekNumber(_currentWeek)}周'
                          : DateFormat('yyyy年MM月dd日').format(_selectedDate),
                  style: const TextStyle(
                                  fontSize: AppTheme.fontSizeXL,
                                  fontWeight: FontWeight.w600,
                                  color: Colors.white,
                  ),
                ),
                              Material(
                                color: Colors.transparent,
                                child: InkWell(
                                  borderRadius: BorderRadius.circular(AppTheme.radiusM),
                                  onTap: _isLatestDate() ? null : () {
                    if (_currentViewMode == StatViewMode.month) {
                      _changeMonth(1);
                    } else if (_currentViewMode == StatViewMode.week) {
                      _changeWeek(1);
                    } else {
                      _changeDate(1);
                    }
                  },
                                  child: Container(
                                    padding: const EdgeInsets.all(AppTheme.paddingS),
                                    decoration: BoxDecoration(
                                      color: _isLatestDate() 
                                          ? Colors.white.withOpacity(0.1)
                                          : Colors.white.withOpacity(0.2),
                                      borderRadius: BorderRadius.circular(AppTheme.radiusM),
                                    ),
                                    child: Icon(
                                      Icons.chevron_right_rounded,
                                      color: _isLatestDate() 
                                          ? Colors.white.withOpacity(0.5)
                                          : Colors.white,
                                      size: 24,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                ),
              ],
                    ),
                  ),
                ),
            ),
          ),

          // 总体统计概览
          Container(
              margin: const EdgeInsets.all(AppTheme.paddingL),
              padding: const EdgeInsets.all(AppTheme.paddingL),
            decoration: BoxDecoration(
                color: AppTheme.cardColor,
                borderRadius: BorderRadius.circular(AppTheme.radiusXL),
                boxShadow: AppTheme.mediumShadow,
            ),
            child: _buildOverallStatistics(),
          ),

          // 统计内容
          Expanded(
            child: SingleChildScrollView(
                padding: const EdgeInsets.fromLTRB(
                  AppTheme.paddingL, 
                  0, 
                  AppTheme.paddingL, 
                  AppTheme.paddingL
                ),
                child: ScaleTransition(
                  scale: _scaleAnimation,
              child: _currentViewMode == StatViewMode.month
                  ? _buildMonthView()
                  : _currentViewMode == StatViewMode.week
                      ? _buildWeekView()
                      : _buildDayView(),
                ),
            ),
          ),
        ],
        ),
      ),
    );
  }

  // 视图模式切换按钮
  Widget _buildViewModeButton(String text, StatViewMode mode) {
    final isSelected = _currentViewMode == mode;
    return Material(
      color: Colors.transparent,
      child: InkWell(
        borderRadius: BorderRadius.circular(AppTheme.radiusM),
      onTap: () => _changeViewMode(mode),
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeInOut,
          padding: const EdgeInsets.symmetric(
            horizontal: AppTheme.paddingM,
            vertical: AppTheme.paddingS,
          ),
        decoration: BoxDecoration(
            color: isSelected 
                ? Colors.white 
                : Colors.transparent,
            borderRadius: BorderRadius.circular(AppTheme.radiusM),
            boxShadow: isSelected ? [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                blurRadius: 4,
                offset: const Offset(0, 2),
              ),
            ] : null,
        ),
        child: Text(
          text,
          style: TextStyle(
              color: isSelected ? AppTheme.primaryColor : Colors.white,
              fontWeight: FontWeight.w600,
              fontSize: AppTheme.fontSizeM,
            ),
          ),
        ),
      ),
    );
  }

  // 获取周数
  int _getWeekNumber(DateTime date) {
    final firstDayOfMonth = DateTime(date.year, date.month, 1);
    final firstWeekday = firstDayOfMonth.weekday;
    final dayOfMonth = date.day;
    return ((dayOfMonth + firstWeekday - 2) ~/ 7) + 1;
  }

  // 月视图
  Widget _buildMonthView() {
    final startDate = _currentMonth;
    final endDate = DateTime(_currentMonth.year, _currentMonth.month + 1, 0);
    final monthTasks = _getTasksInRange(startDate, endDate);
    final stats = _getStats(monthTasks);

    return Column(
      children: [
        _buildSummaryCards(stats),
        const SizedBox(height: 24),
        _buildCompletionChart(stats),
        const SizedBox(height: 24),
        _buildTimingChart(stats),
      ],
    );
  }

  // 周视图
  Widget _buildWeekView() {
    final startDate = _currentWeek;
    final endDate = _currentWeek.add(const Duration(days: 6));
    final weekTasks = _getTasksInRange(startDate, endDate);
    final stats = _getStats(weekTasks);

    return Column(
      children: [
        _buildSummaryCards(stats),
        const SizedBox(height: 24),
        _buildCompletionChart(stats),
        const SizedBox(height: 24),
        _buildTimingChart(stats),
      ],
    );
  }

  // 日视图
  Widget _buildDayView() {
    final startDate = _selectedDate;
    final endDate = _selectedDate;
    final dayTasks = _getTasksInRange(startDate, endDate);
    final stats = _getStats(dayTasks);

    return Column(
      children: [
        _buildSummaryCards(stats),
        const SizedBox(height: 24),
        _buildCompletionChart(stats),
        const SizedBox(height: 24),
        _buildTimingChart(stats),
      ],
    );
  }

  // 统计卡片
  Widget _buildSummaryCards(Map<String, dynamic> stats) {
    return FadeTransition(
      opacity: _fadeAnimation,
      child: Row(
      children: [
        _buildSummaryCard(
          '总任务数',
          '${stats['total']}',
            AppTheme.infoColor,
            Icons.list_alt_rounded,
            LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [AppTheme.infoColor, Color(0xFF2563EB)],
            ),
        ),
          const SizedBox(width: AppTheme.paddingL),
        _buildSummaryCard(
          '已完成',
          '${stats['completed']}',
            AppTheme.successColor,
            Icons.check_circle_rounded,
            AppTheme.successGradient,
        ),
          const SizedBox(width: AppTheme.paddingL),
        _buildSummaryCard(
          '完成率',
          '${(stats['completionRate'] * 100).toStringAsFixed(1)}%',
            AppTheme.primaryColor,
            Icons.pie_chart_rounded,
            AppTheme.primaryGradient,
        ),
      ],
      ),
    );
  }

  // 单个统计卡片
  Widget _buildSummaryCard(String label, String value, Color color, IconData icon, LinearGradient gradient) {
    return Expanded(
      child: Container(
        padding: const EdgeInsets.all(AppTheme.paddingL),
        decoration: BoxDecoration(
          gradient: gradient,
          borderRadius: BorderRadius.circular(AppTheme.radiusL),
          boxShadow: [
            BoxShadow(
              color: color.withOpacity(0.3),
              blurRadius: 12,
              offset: const Offset(0, 6),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              padding: const EdgeInsets.all(AppTheme.paddingS),
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.25),
                borderRadius: BorderRadius.circular(AppTheme.radiusM),
              ),
              child: Icon(
                icon, 
                color: Colors.white, 
                size: 20,
            ),
            ),
            const SizedBox(height: AppTheme.paddingM),
            Text(
              value,
              style: const TextStyle(
                fontSize: AppTheme.fontSizeXXL,
                fontWeight: FontWeight.w700,
                color: Colors.white,
              ),
            ),
            const SizedBox(height: AppTheme.paddingXS),
            Text(
              label,
              style: const TextStyle(
                fontSize: AppTheme.fontSizeS,
                color: Colors.white,
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 完成率饼图
  Widget _buildCompletionChart(Map<String, dynamic> stats) {
    final completionRate = stats['total'] > 0 ? (stats['completed'] / stats['total']) : 0.0;
    final completionPercentage = (completionRate * 100).round();
    
    return FadeTransition(
      opacity: _fadeAnimation,
      child: Container(
        // 移除固定高度，让内容自适应
        margin: const EdgeInsets.symmetric(
          horizontal: AppTheme.paddingL,
          vertical: AppTheme.paddingL, // 增加垂直边距
        ),
        padding: const EdgeInsets.all(AppTheme.paddingXXL), // 增加内边距
      decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              Colors.white,
              Color(0xFFFAFBFC),
            ],
          ),
          borderRadius: BorderRadius.circular(AppTheme.radiusXXL),
          boxShadow: [
            BoxShadow(
              color: AppTheme.primaryColor.withOpacity(0.08),
              blurRadius: 20,
              offset: const Offset(0, 10),
              spreadRadius: 0,
            ),
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 40,
              offset: const Offset(0, 20),
              spreadRadius: -10,
            ),
          ],
          border: Border.all(
        color: Colors.white,
            width: 2,
          ),
        ),
        child: Column(
          children: [
            // 头部区域
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(AppTheme.paddingM),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                      colors: [
                        AppTheme.primaryColor,
                        Color(0xFF7C3AED),
                      ],
                    ),
                    borderRadius: BorderRadius.circular(AppTheme.radiusL),
        boxShadow: [
          BoxShadow(
                        color: AppTheme.primaryColor.withOpacity(0.4),
                        blurRadius: 12,
                        offset: const Offset(0, 6),
          ),
        ],
      ),
                  child: const Icon(
                    Icons.analytics_rounded,
                    color: Colors.white,
                    size: 24,
                  ),
                ),
                const SizedBox(width: AppTheme.paddingL),
                Expanded(
      child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '任务完成率',
            style: TextStyle(
                          fontSize: AppTheme.fontSizeXL,
                          fontWeight: FontWeight.w800,
                          color: AppTheme.textPrimaryColor,
            ),
          ),
                      const SizedBox(height: 4),
                      Text(
                        '当前统计周期数据分析',
                        style: TextStyle(
                          fontSize: AppTheme.fontSizeS,
                          color: AppTheme.textSecondaryColor,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                ),
                // 右上角完成率徽章
                Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: AppTheme.paddingL,
                    vertical: AppTheme.paddingM,
                  ),
                  decoration: BoxDecoration(
                    gradient: _getCompletionGradient(completionRate),
                    borderRadius: BorderRadius.circular(AppTheme.radiusXL),
                    boxShadow: [
                      BoxShadow(
                        color: _getCompletionColor(completionRate).withOpacity(0.4),
                        blurRadius: 12,
                        offset: const Offset(0, 6),
                      ),
                    ],
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(
                        _getCompletionIcon(completionRate),
                        color: Colors.white,
                        size: 18,
                      ),
                      const SizedBox(width: 6),
                      Text(
                        '$completionPercentage%',
                        style: const TextStyle(
                          fontSize: AppTheme.fontSizeL,
                          fontWeight: FontWeight.w800,
                          color: Colors.white,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: AppTheme.paddingXL), // 适中的间距
            
            // 饼图区域
            SizedBox(
              height: 220, // 再次减小饼图区域高度
              child: ScaleTransition(
                scale: _scaleAnimation,
                child: Stack(
                  children: [
                    // 饼图
                    PieChart(
                PieChartData(
                        sectionsSpace: 14, // 再次减小分割间距
                        centerSpaceRadius: 60, // 再次减小中心空间
                        startDegreeOffset: -90,
                        pieTouchData: PieTouchData(
                          enabled: true,
                          touchCallback: (FlTouchEvent event, pieTouchResponse) {
                            if (pieTouchResponse?.touchedSection != null) {
                              // 添加触摸反馈
                            }
                          },
                        ),
                  sections: stats['total'] == 0 ? [
                    PieChartSectionData(
                      value: 1,
                            color: Color(0xFFF3F4F6),
                            title: '',
                            radius: 65, // 再次减小半径
                            borderSide: const BorderSide(
                        color: Colors.white,
                              width: 4,
                      ),
                    ),
                  ] : [
                    if (stats['completed'] > 0)
                      PieChartSectionData(
                        value: stats['completed'].toDouble(),
                              color: Color(0xFF10B981), // 使用纯色而不是渐变
                              title: '',
                              radius: 65, // 再次减小半径
                              borderSide: const BorderSide(
                          color: Colors.white,
                                width: 6, // 增加边框宽度
                        ),
                      ),
                    if ((stats['total'] - stats['completed']) > 0)
                      PieChartSectionData(
                        value: (stats['total'] - stats['completed']).toDouble(),
                              color: Color(0xFFE5E7EB), // 使用纯色
                              title: '',
                              radius: 65, // 再次减小半径
                              borderSide: const BorderSide(
                          color: Colors.white,
                                width: 6, // 增加边框宽度
                        ),
                      ),
                  ],
                ),
              ),
                    
                    // 中心显示区域
                    Positioned.fill(
                      child: Center(
                        child: Container(
                          width: 115, // 再次减小中心圆的尺寸
                          height: 115,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            shape: BoxShape.circle,
                            boxShadow: [
                              BoxShadow(
                                color: Colors.black.withOpacity(0.1),
                                blurRadius: 25,
                                offset: const Offset(0, 10),
                              ),
                              BoxShadow(
                                color: _getCompletionColor(completionRate).withOpacity(0.15),
                                blurRadius: 15,
                                offset: const Offset(0, 5),
                              ),
                            ],
                            border: Border.all(
                              color: Colors.white,
                              width: 6,
                            ),
                          ),
                          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
                              // 主要百分比
                              Text(
                                '$completionPercentage%',
                                style: TextStyle(
                                  fontSize: 28, // 再次减小字体大小
                                  fontWeight: FontWeight.w900,
                                  color: _getCompletionColor(completionRate),
                                  height: 1.0,
                                ),
                              ),
                              const SizedBox(height: 4),
                              // 标签
                              Text(
                                '完成率',
                                style: TextStyle(
                                  fontSize: AppTheme.fontSizeS,
                                  fontWeight: FontWeight.w600,
                                  color: AppTheme.textSecondaryColor,
                                ),
                              ),
                              const SizedBox(height: 8),
                              // 状态指示器
                              Container(
                                height: 3,
                                width: 40,
                                decoration: BoxDecoration(
                                  color: _getCompletionColor(completionRate),
                                  borderRadius: BorderRadius.circular(2),
                                ),
                              ),
                              const SizedBox(height: 4),
                              // 状态文字
                              Text(
                                _getCompletionStatusText(completionRate),
                                style: TextStyle(
                                  fontSize: AppTheme.fontSizeXS,
                                  fontWeight: FontWeight.w600,
                                  color: _getCompletionColor(completionRate),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                    
                    // 分割线指示器（可选）
                    if (stats['total'] > 0 && stats['completed'] > 0 && (stats['total'] - stats['completed']) > 0)
                      Positioned.fill(
                        child: CustomPaint(
                          painter: PieSeparatorPainter(
                            completionRate: completionRate,
                            centerRadius: 60, // 再次更新中心半径
                            outerRadius: 65, // 再次更新外边半径
                          ),
                        ),
                      ),
                  ],
                ),
              ),
            ),
            
            const SizedBox(height: AppTheme.paddingL), // 减少间距避免溢出
            
            // 底部详情卡片
            IntrinsicHeight( // 确保所有卡片高度一致
              child: Row(
                children: [
                Expanded(
                  child: _buildModernDetailCard(
                    '已完成',
                    '${stats['completed']}',
                    Color(0xFF10B981),
                    Icons.check_circle_rounded,
                    true,
                  ),
                ),
                const SizedBox(width: AppTheme.paddingL), // 增加卡片间距
                Expanded(
                  child: _buildModernDetailCard(
                    '未完成',
                    '${stats['total'] - stats['completed']}',
                    Color(0xFF94A3B8),
                    Icons.schedule_rounded,
                    false,
                  ),
                ),
                const SizedBox(width: AppTheme.paddingL), // 增加卡片间距
                Expanded(
                  child: _buildModernDetailCard(
                    '总任务',
                    '${stats['total']}',
                    AppTheme.infoColor,
                    Icons.list_alt_rounded,
                    false,
                  ),
          ),
        ],
                ),
            ),
          ],
        ),
      ),
    );
  }

  // 获取完成率对应的颜色
  Color _getCompletionColor(double rate) {
    if (rate >= 0.8) return Color(0xFF10B981);  // 绿色
    if (rate >= 0.5) return Color(0xFFF59E0B);  // 橙色
    return Color(0xFFEF4444);  // 红色
  }

  // 获取完成率对应的渐变
  LinearGradient _getCompletionGradient(double rate) {
    if (rate >= 0.8) {
      return LinearGradient(
        colors: [Color(0xFF10B981), Color(0xFF059669)],
      );
    }
    if (rate >= 0.5) {
      return LinearGradient(
        colors: [Color(0xFFF59E0B), Color(0xFFD97706)],
      );
    }
    return LinearGradient(
      colors: [Color(0xFFEF4444), Color(0xFFDC2626)],
    );
  }

  // 获取完成率对应的图标
  IconData _getCompletionIcon(double rate) {
    if (rate >= 0.8) return Icons.celebration_rounded;
    if (rate >= 0.5) return Icons.trending_up_rounded;
    return Icons.trending_down_rounded;
  }

  // 获取完成率状态文字
  String _getCompletionStatusText(double rate) {
    if (rate >= 0.8) return '优秀';
    if (rate >= 0.5) return '良好';
    return '待改进';
  }

  // 现代化详情卡片
  Widget _buildModernDetailCard(
    String label,
    String value,
    Color color,
    IconData icon,
    bool isHighlight,
  ) {
    return Container(
      // 移除固定高度，让内容自适应
      padding: const EdgeInsets.all(AppTheme.paddingM), // 减少内边距
      decoration: BoxDecoration(
        gradient: isHighlight 
            ? LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  color.withOpacity(0.1),
                  color.withOpacity(0.05),
                ],
              )
            : LinearGradient(
                colors: [
                  Color(0xFFFAFBFC),
                  Colors.white,
                ],
              ),
        borderRadius: BorderRadius.circular(AppTheme.radiusL),
        border: Border.all(
          color: isHighlight 
              ? color.withOpacity(0.3) 
              : Color(0xFFE5E7EB),
          width: 1.5,
        ),
        boxShadow: [
          BoxShadow(
            color: isHighlight 
                ? color.withOpacity(0.1) 
                : Colors.black.withOpacity(0.03),
            blurRadius: 8,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min, // 最小尺寸，紧凑排列
        mainAxisAlignment: MainAxisAlignment.center, // 居中对齐避免溢出
        children: [
          Container(
            padding: const EdgeInsets.all(AppTheme.paddingXS), // 减少图标容器的内边距
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [color, color.withOpacity(0.8)],
              ),
              borderRadius: BorderRadius.circular(AppTheme.radiusM),
              boxShadow: [
                BoxShadow(
                  color: color.withOpacity(0.3),
                  blurRadius: 6,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Icon(
              icon,
              color: Colors.white,
              size: 18, // 减小图标尺寸
            ),
          ),
          const SizedBox(height: AppTheme.paddingS), // 减少间距
          RichText(
            text: TextSpan(
              children: [
                TextSpan(
                  text: value,
                  style: TextStyle(
                    fontSize: AppTheme.fontSizeL, // 减小字体
                    fontWeight: FontWeight.w800,
                    color: color,
                    height: 1.0,
                  ),
                ),
                TextSpan(
                  text: '个',
                  style: TextStyle(
                    fontSize: AppTheme.fontSizeXS, // 减小单位字体
                    fontWeight: FontWeight.w500,
                    color: AppTheme.textSecondaryColor,
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: AppTheme.paddingXS), // 保持小间距
          Text(
            label,
            style: TextStyle(
              fontSize: AppTheme.fontSizeXS, // 减小标签字体
              color: AppTheme.textSecondaryColor,
              fontWeight: FontWeight.w600,
            ),
          ),
        ],
      ),
    );
  }

  // 时间分布柱状图
  Widget _buildTimingChart(Map<String, dynamic> stats) {
    return FadeTransition(
      opacity: _fadeAnimation,
      child: Container(
        height: 320,
        padding: const EdgeInsets.all(AppTheme.paddingXL),
        decoration: BoxDecoration(
          color: AppTheme.cardColor,
          borderRadius: BorderRadius.circular(AppTheme.radiusXL),
          boxShadow: AppTheme.mediumShadow,
          border: Border.all(
            color: AppTheme.primaryColor.withOpacity(0.1),
            width: 1,
          ),
        ),
        child: Column(
          children: [
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(AppTheme.paddingS),
                  decoration: BoxDecoration(
                    gradient: AppTheme.warningGradient,
                    borderRadius: BorderRadius.circular(AppTheme.radiusM),
                    boxShadow: [
                      BoxShadow(
                        color: AppTheme.warningColor.withOpacity(0.3),
                        blurRadius: 8,
                        offset: const Offset(0, 4),
                      ),
                    ],
                  ),
                  child: const Icon(
                    Icons.schedule_rounded,
                    color: Colors.white,
                    size: 20,
                  ),
                ),
                const SizedBox(width: AppTheme.paddingM),
          const Text(
            '任务完成时间分布',
            style: TextStyle(
                    fontSize: AppTheme.fontSizeXL,
                    fontWeight: FontWeight.w700,
                    color: AppTheme.textPrimaryColor,
            ),
          ),
              ],
            ),
            const SizedBox(height: AppTheme.paddingL),
          Expanded(
              child: ScaleTransition(
                scale: _scaleAnimation,
            child: BarChart(
              BarChartData(
                alignment: BarChartAlignment.spaceAround,
                    maxY: (stats['completed'] > 0 ? stats['completed'] : 1).toDouble(),
                    barTouchData: BarTouchData(
                      enabled: true,
                      touchTooltipData: BarTouchTooltipData(
                        tooltipBgColor: AppTheme.primaryColor.withOpacity(0.9),
                        tooltipRoundedRadius: AppTheme.radiusM,
                        getTooltipItem: (group, groupIndex, rod, rodIndex) {
                          return BarTooltipItem(
                            '${rod.toY.round()}个任务',
                            const TextStyle(
                              color: Colors.white,
                              fontSize: AppTheme.fontSizeS,
                              fontWeight: FontWeight.w600,
                            ),
                          );
                        },
                      ),
                    ),
                titlesData: FlTitlesData(
                  show: true,
                  bottomTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      getTitlesWidget: (value, meta) {
                        const titles = ['提前完成', '按时完成', '超时完成'];
                        return Padding(
                              padding: const EdgeInsets.only(top: AppTheme.paddingS),
                          child: Text(
                            titles[value.toInt()],
                            style: const TextStyle(
                                  color: AppTheme.textSecondaryColor,
                                  fontSize: AppTheme.fontSizeS,
                                  fontWeight: FontWeight.w600,
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                  leftTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                          reservedSize: 40,
                          getTitlesWidget: (value, meta) {
                            return Text(
                              value.toInt().toString(),
                              style: const TextStyle(
                                color: AppTheme.textSecondaryColor,
                                fontSize: AppTheme.fontSizeXS,
                                fontWeight: FontWeight.w500,
                              ),
                            );
                          },
                    ),
                  ),
                  topTitles: AxisTitles(
                    sideTitles: SideTitles(showTitles: false),
                  ),
                  rightTitles: AxisTitles(
                    sideTitles: SideTitles(showTitles: false),
                  ),
                ),
                borderData: FlBorderData(show: false),
                    gridData: FlGridData(
                      show: true,
                      drawVerticalLine: false,
                      horizontalInterval: 1,
                      getDrawingHorizontalLine: (value) {
                        return FlLine(
                          color: AppTheme.borderColor,
                          strokeWidth: 1,
                        );
                      },
                    ),
                barGroups: [
                  BarChartGroupData(
                    x: 0,
                    barRods: [
                      BarChartRodData(
                        toY: stats['early'].toDouble(),
                            gradient: AppTheme.successGradient,
                            width: 24,
                        borderRadius: const BorderRadius.vertical(
                              top: Radius.circular(AppTheme.radiusS),
                        ),
                      ),
                    ],
                  ),
                  BarChartGroupData(
                    x: 1,
                    barRods: [
                      BarChartRodData(
                        toY: stats['onTime'].toDouble(),
                            gradient: LinearGradient(
                              begin: Alignment.bottomCenter,
                              end: Alignment.topCenter,
                              colors: [AppTheme.infoColor, Color(0xFF2563EB)],
                            ),
                            width: 24,
                        borderRadius: const BorderRadius.vertical(
                              top: Radius.circular(AppTheme.radiusS),
                        ),
                      ),
                    ],
                  ),
                  BarChartGroupData(
                    x: 2,
                    barRods: [
                      BarChartRodData(
                        toY: stats['late'].toDouble(),
                            gradient: LinearGradient(
                              begin: Alignment.bottomCenter,
                              end: Alignment.topCenter,
                              colors: [AppTheme.errorColor, Color(0xFFDC2626)],
                            ),
                            width: 24,
                        borderRadius: const BorderRadius.vertical(
                              top: Radius.circular(AppTheme.radiusS),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
            ),
            const SizedBox(height: AppTheme.paddingL),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
                _buildLegendItem(AppTheme.successColor, '提前完成'),
                const SizedBox(width: AppTheme.paddingL),
                _buildLegendItem(AppTheme.infoColor, '按时完成'),
                const SizedBox(width: AppTheme.paddingL),
                _buildLegendItem(AppTheme.errorColor, '超时完成'),
            ],
          ),
        ],
        ),
      ),
    );
  }

  // 图例项
  Widget _buildLegendItem(Color color, String label) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          width: 12,
          height: 12,
          decoration: BoxDecoration(
            color: color,
            borderRadius: BorderRadius.circular(AppTheme.radiusXS),
            boxShadow: [
              BoxShadow(
                color: color.withOpacity(0.3),
                blurRadius: 4,
                offset: const Offset(0, 2),
              ),
            ],
          ),
        ),
        const SizedBox(width: AppTheme.paddingS),
        Text(
          label,
          style: const TextStyle(
            fontSize: AppTheme.fontSizeS,
            color: AppTheme.textSecondaryColor,
            fontWeight: FontWeight.w500,
          ),
        ),
      ],
    );
  }
}

// 自定义绘制器，用于绘制分割线
class PieSeparatorPainter extends CustomPainter {
  final double completionRate;
  final double centerRadius;
  final double outerRadius;

  PieSeparatorPainter({
    required this.completionRate,
    required this.centerRadius,
    required this.outerRadius,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final paint = Paint()
      ..color = Colors.white
      ..strokeWidth = 3
      ..style = PaintingStyle.stroke;

    // 计算分割线的角度
    final angle = (completionRate * 2 * 3.14159) - (3.14159 / 2); // -90度开始
    
    // 绘制分割线
    final startPoint = Offset(
      center.dx + centerRadius * cos(angle),
      center.dy + centerRadius * sin(angle),
    );
    final endPoint = Offset(
      center.dx + outerRadius * cos(angle),
      center.dy + outerRadius * sin(angle),
    );
    
    canvas.drawLine(startPoint, endPoint, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}